#!/usr/bin/env python


import os
import pygtk
import gtk
pygtk.require("2.0")
import gtk,gobject
import gtk.glade,gtk.gdk
import time , datetime

config_file="/.jdesktop/config.config"
config_dir="/.jdesktop/"
pixdir="/usr/share/pixmaps/jdesktop/"
datadir="/usr/share/jdesktop/"
def get_time():
    return time.gmtime()
class TrackerStatusIcon:
    _version="0.0.1.svn"
    timerRate=1000
    def __init__(self):
        global datadir 
        global pixdir
        self.wMenuTree=gtk.glade.XML(datadir+"interface.glade","pppMenu")
        self.wTree=gtk.glade.XML(datadir+"interface.glade")
        self.windowPre = self.wTree.get_widget("preferences")
        mdict={"on_btnClose_activate":self.on_btnClose_active,
               "on_btnAddImage_activate":self.on_btnAddImage_activate,
               "on_button6_activate":self.refreshMyDesktop,
               "on_cmboLocation_changed":self.refreshMyDesktop
               }
        #self.wTree.signal_autoconnect(mdict) 
        #I dont exactly why it didnot work  !
        #so I connect my element's by coding
        
        
        self.windowPre.connect("destroy",self.on_btnClose_active)
        
        self.btnClose=self.wTree.get_widget("btnClose")
        self.btnClose.connect("clicked",self.on_btnClose_active)
        self.cmboLocation=self.wTree.get_widget("cmboLocation")
        self.cmboLocation.connect("changed",self.on_cmboLocation_changed)
        
        self.btnAddImage=self.wTree.get_widget("btnAddImage")
        self.btnAddImage.connect("clicked",self.on_btnAddImage_activate)
        
        self.btnRemoveImage=self.wTree.get_widget("btnRemoveImage")
        self.btnRemoveImage.connect("clicked",self.on_btnRemoveImage_activate)
        
        self.btnApplyImage=self.wTree.get_widget("btnApplyImage")
        self.btnRemoveImage.connect("clicked",self.on_btnApplyImage_activate)
        
        mdictMenu={"on_btnQuit_activate":gtk.main_quit,
               "on_btnAbout_activate":self.openDialogAbout,
               "on_btnPreferences_activate":self.openDialogPreferences,
               "on_btnrefreshmydesktop_activate":self.refreshMyDesktop
               }
        self.wMenuTree.signal_autoconnect(mdictMenu) 
        
        self.runFirstTime=False
        #load config
        self.loadConfig()
        self.lastUpdate=get_time()
        self.lastCheck=None
        gobject.timeout_add(self.timerRate, self.checkChanges)
        global pixdir
        #load icon
        self.statusIcon = gtk.StatusIcon()
        self.statusIcon.set_from_file(pixdir+"jdesktop.png")
        self.set_tooltip()
        self.statusIcon.connect('popup-menu', self.on_popup_menu)
        self.statusIcon.connect('activate', self.refreshMyDesktop)
        
        #load TreeView
        self.treestore = gtk.ListStore(str,str)
        self.treeview=self.wTree.get_widget("tvImages")
        self.treeview.set_model(self.treestore)
        self.cell = gtk.CellRendererText()
        col = gtk.TreeViewColumn("Images",self.cell,text=0)
        self.treeview.append_column(col)
        self.treeview.set_search_column(0)        
        if self.runFirstTime==True:
            self.openDialogPreferences("nothing")
            
             
    def set_tooltip(self):
        if self.refreshTime==0:
            self.statusIcon.set_tooltip("jDesktop\nWallpaper change every day")
        else :
            self.statusIcon.set_tooltip("jDesktop\nWallpaper change in every "+self.refreshTime.__str__()+" minuts")
    def checkChanges(self):
        self.lastCheck=time.gmtime()
        intMKLastCheck=int(time.mktime(self.lastCheck))
        intMKLastUpdate=int(time.mktime(self.lastUpdate))
        
        if self.lastCheck[2] != self.lastUpdate[2]:
            print "change desktop...."
            self.refreshMyDesktop("nothing")
            self.lastUpdate=self.lastCheck            
            return True
        
        if self.refreshTime==0:
            return True
        diffSecond= ( self.refreshTime *60)
        if (intMKLastCheck - intMKLastUpdate)>= diffSecond :
            print "change desktop...."
            self.refreshMyDesktop("nothing")
            self.lastUpdate=self.lastCheck            
            return True            
        
        return True

    def getHome(self):
        return os.environ.get('HOME', '')
    
    def loadConfig(self):
        global config_file
        
        try :
            fHandler=open(self.getHome()+config_file,'r')
            #read times to refresh
            buff=fHandler.readline()
            self.refreshTime=int(buff)
            
            #read postion
            buff=fHandler.readline()
            self.position=buff.split("\n")[0]
            
            #read X,Y
            buff=fHandler.readline()
            tmpStr=buff.split(";")
            self.X=int(tmpStr[0])
            self.Y=int(tmpStr[1])
            
            #reads images
            self.images=[]
            while 1:
                buff=fHandler.readline()
                if buff:
                    self.images.append(buff)
                else:
                    break
            fHandler.close()
        except IOError:
            self.refreshTime=0
            self.position='Top Right(Auto)'
            self.X=0
            self.Y=0
            self.images=[]
            self.images.append("/usr/share/pixmaps/jdesktop/default.jpg\n")
#            self.saveConfig()
#            self.refreshMyDesktop("nothing")
            self.runFirstTime=True
            print "error reading file"
      
    def saveConfig(self):
        global config_file,config_dir
        
        #check If directory not exist create it
        try:
            os.mkdir( self.getHome()+config_dir)
        except OSError:
            print "Directory exist skip creating it"

        try :
            fHandler=open(self.getHome()+config_file,'w')
            refTime=int(self.sbtnTimer.get_value())
            fHandler.writelines(refTime.__str__()+"\n")
            #print self.sbtnTimer.get_value()
            if self.cmboLocation.get_active()==0:
                fHandler.writelines(self.cmboLocation.get_active_text()+"\n")
                fHandler.writelines(self.txtXLoc.get_text()+";"+self.txtYLoc.get_text()+"\n")
            else :
                fHandler.writelines(self.cmboLocation.get_active_text()+"\n")
                fHandler.writelines("5;5"+"\n")
            #print self.treestore
            for image in self.images:
                fHandler.writelines( image)
                
            fHandler.close()
            self.loadConfig()
            self.set_tooltip()
        except IOError:
            pass   
        
    def on_btnApplyImage_activate(self,widget):
        print "will select this photo"
       
        pass

    def on_cmboLocation_changed(self,widget):
        if self.cmboLocation.get_active()==0:
            self.txtXLoc.set_editable(True)
            self.txtYLoc.set_editable(True)
        else:
            self.txtXLoc.set_editable(False)
            self.txtYLoc.set_editable(False)            
            pass
    def refreshMyDesktop(self,widget): 
        os.system('php '+ datadir+'calendar.php') 
        os.system('gconftool-2 -s /desktop/gnome/background/picture_filename "'+self.getHome()+'/.jdesktop/out.png" -t string');
        
    def openDialogPreferences(self,widget): 
        
        #Top Right(Auto)
        self.sbtnTimer=self.wTree.get_widget("sbtnTimer")
        self.sbtnTimer.set_value(self.refreshTime)
        #
        self.txtXLoc=self.wTree.get_widget("txtXLoc")
        self.txtYLoc=self.wTree.get_widget("txtYLoc")
        if self.position=='Custom':
            self.txtXLoc.set_text(self.X.__str__())
            self.txtYLoc.set_text(self.Y.__str__())
            self.cmboLocation.set_active(0)
        elif self.position=='Top Right(Auto)':
            self.cmboLocation.set_active(1)
        #and other location ....
        
        #set listBox
        self.treestore.clear()
        for image in self.images:
            image=image.split('\n')[0]
            self.treestore.append([image,image])
        
        #self.windowPre.show()
        
        self.windowPre.set_property("skip-taskbar-hint", False)
        self.windowPre.present()        
        
        pass
    
    def on_btnAddImage_activate(self,widget):
        dialog = gtk.FileChooserDialog("Please select Wallpaper ( 1024*768 )",
                               None,
                               gtk.FILE_CHOOSER_ACTION_OPEN,
                               (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        dialog.set_default_response(gtk.RESPONSE_OK)

        
 
        filter = gtk.FileFilter()
        filter.set_name("Images")
        filter.add_mime_type("image/png")
        filter.add_mime_type("image/jpeg")
        filter.add_mime_type("image/gif")
        filter.add_pattern("*.png")
        filter.add_pattern("*.jpg")
        filter.add_pattern("*.gif")
 
        
 
        dialog.add_filter(filter)

        
        filter = gtk.FileFilter()
        filter.set_name("All files")
        filter.add_pattern("*")
        dialog.add_filter(filter)
                
        response = dialog.run()
        if response == gtk.RESPONSE_OK:
            pass
            self.treestore.append([dialog.get_filename(),dialog.get_filename()])  
            self.images.append(dialog.get_filename()+'\n')          
        elif response == gtk.RESPONSE_CANCEL:
            pass
        dialog.destroy()
        
    def on_btnRemoveImage_activate(self,widget): 
        selection=self.treeview.get_selection()
        (mode,iter)=selection.get_selected()
        if iter:
            word=mode.get(iter,1)[0]
            #self.connectAddress=word
            #self.txtDeviceName.set_text(mode.get(iter,0)[0])
            #print  word   
            try:
                self.images.remove(word+"\n")
            except ValueError:
                print "can not find index array"
        self.treestore.clear()
        for image in self.images:
            image=image.split('\n')[0]
            self.treestore.append([image,image])  
            
                      
    def on_btnClose_active(self,widget):
        self.saveConfig()
        #self.windowPre.destroy()
        self.windowPre.hide()
        #self.windowPre.destroy()

    def openDialogAbout(self,widget):
        
        
       
        dialog = gtk.AboutDialog()
        dialog.set_name('Gnome jDesktop')
        dialog.set_version(self._version)
        dialog.set_comments('Jalali calender on your desktop')
        dialog.set_website('http://jdesktop.gnudownload.org')
        dialog.set_license("jDesktop is free software;\nyou can redistribute it and/or modify it\nunder the terms of the GNU General Public License\nas published by the Free Software Foundation; \neither version 2 of the License")
        dialog.set_authors(["Pedram Azimaie <pedram@gnudownload.org>","Milad Rastin <milad@rastian.com>"]) 
        dialog.run()
        dialog.destroy()
       
        
    def on_popup_menu(self, obj, button, time):
        menu=self.wMenuTree.get_widget("pppMenu")
        menu.popup(None,None,None,button,time) 
                


if __name__ == '__main__':
    TrackerStatusIcon()
    gtk.main()

